/**
 * 
 */
package design_pattern.flyweight.composite;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

/**
 * @author linzq
 * 
 */
public class FlyweightFactory {

  private HashMap files = new HashMap();

  private Flyweight inFlyweight = null;

  public FlyweightFactory() {}

  public ConcreteCompositeFlyweight factory(String strState) {
    ConcreteCompositeFlyweight compositeFly = new ConcreteCompositeFlyweight();
    int length = strState.length();
    Character state = null;
    Flyweight fly = null;
    for (int i = 0; i < length; i++) {
      state = strState.charAt(i);
      compositeFly.add(state, factory(state));// 使叶子享元工厂方法。
    }
    return compositeFly;
  }

  public Flyweight factory(Character state) {
    if (files.containsKey(state)) {
      return (Flyweight) files.get(state);
    } else {
      Flyweight fly = new ConcreteFlyweight(state);
      files.put(state, fly);
      return fly;
    }
  }

  @Override
  protected void finalize() throws Throwable {
    files = null;
    inFlyweight = null;
    super.finalize();
  }

  public void checkFlyweight() {
    Flyweight fly = null;
    int i = 0;
    System.out.println("\n==========checkFlyweight()===========");
    for (Iterator it = files.entrySet().iterator(); it.hasNext();) {
      Map.Entry e = (Map.Entry) it.next();
      System.out.println("Item" + (++i) + ":" + e.getKey());
    }
    System.out.println("\n==========checkFlyweight()===========");
  }
}
